package com.springboot.demo.task;


import cn.hutool.core.util.StrUtil;
import com.cx.item.common.cache.redis.RedisTaskServiceUtil;
import com.springboot.demo.model.constants.SunMiniappRedisConstants;
import com.springboot.demo.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.net.InetAddress;

/**
 * 每天凌晨执行任务，查询数据库所有有效用户token保存在redis缓存中
 * Created by hwm on 2018/7/2.
 */
@Slf4j
@Component
public class InitCustomerTokenTask {

    @Autowired
    private CustomerService customerService;
    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;

    private String initCustomerTokenTaskLock = SunMiniappRedisConstants.staticConstantNumber + "initCustomerTokenLock";

    @Scheduled(cron = "0 0 3 * * ?")
    public void initCustomerTokenTask(){

        String hostaddress = "127.0.0.1";
        // 获取jedis
        Jedis jedis = jedisConnectionFactory.getShardInfo().createResource();
        try {
            InetAddress address = InetAddress.getLocalHost();
            hostaddress = address.getHostAddress();

            // 获取执行锁
            if (!RedisTaskServiceUtil.tryGetDistributedLock(jedis, initCustomerTokenTaskLock, hostaddress, 30000)){
                log.debug(StrUtil.format("===================================>执行锁【{}】已被{}集群服务器获取", initCustomerTokenTaskLock, jedis.get(initCustomerTokenTaskLock)));
                return;
            }else {
                log.debug(StrUtil.format("===================================>集群服务器{}成功获得锁【{}】", hostaddress, initCustomerTokenTaskLock));
                log.debug("================================防止获取锁时间有差别，执行initCustomerTokenTask方法后立即释放锁，程序休眠10秒==============================");
                Thread.sleep(10000);
                log.debug("==================执行initCustomerTokenTask方法begin==================");
            }

            // 初始化用户token
            log.debug("===================================>初始化用户token开始");
            long l = customerService.initCustomerToken();
            log.debug("<===================================初始化用户token结束,redis token数量" + l);

        }catch (Exception e){
            log.error("===================================>initCustomerToken方法发生异常，重新执行bedin", e);
            customerService.initCustomerToken();
            log.error("<===================================initCustomerToken方法发生异常，重新执行end", e);
        }finally {
            if (RedisTaskServiceUtil.releaseDistributedLock(jedis, initCustomerTokenTaskLock, hostaddress)){
                log.debug(StrUtil.format("<===================================集群服务器{}成功释放锁【{}】，执行initCustomerTokenTask方法end", hostaddress, initCustomerTokenTaskLock));
            }
        }
    }
}

